package com.coolwar.design.proxy.dynamic.jdk;


import com.coolwar.design.proxy.dynamic.Action;
import com.coolwar.design.proxy.dynamic.IAction;

import java.lang.reflect.Proxy;


/**
 * @author Coolwar
 * 动态代理
 */
public class ProxyFactory {

    private final Object target;

    public ProxyFactory(Object o) {
        this.target = o;
    }

    public Object getProxyInstance() {
        return Proxy.newProxyInstance(
                target.getClass().getClassLoader(),
                target.getClass().getInterfaces(),
                (proxy, method, objects) -> {
                    System.out.println("开始事务");
                    Object invoke = method.invoke(target, objects);
                    System.out.println("提交事务");
                    return invoke;
                });
    }

    public static void main(String[] args) {
        IAction action = (IAction) new ProxyFactory(new Action()).getProxyInstance();
        action.sing();
    }
}
